<template>
	<view class="ready">
		<u-navbar title="开始艾灸" bgColor="transparent" safeAreaInsetTop :placeholder="true" leftIconColor="#000000"
			@leftClick="back" titleStyle="{fontSize: 16px;font-weight: bold;color: #000000;}">
		</u-navbar>
		<view class="contents" v-if="detail">
			<view class="progressBar" v-if="detail.is_activate">
				<!-- <view class="progressBars">
					<view class="fontText">
						可获得元气 {{detail.score.current_score}}/{{detail.score.max_score}}
					</view>
					<view class="progress">
						<u-line-progress :percentage="Math.round(detail.score.current_score / detail.score.max_score * 10000) / 100.00" :showText="false"
							:activeColor="'linear-gradient(90deg, #89D1F5 0%, #C4EFFA 100%)'" />
					</view>
				</view> -->
				
				<view class="progressBars">
					<view class="fontText">
						今日可消耗能量 {{detail.power.current_power}}/{{detail.power.max_power}}
					</view>
					<view class="progress" v-if="detail.power.current_power">
						<u-line-progress :percentage="Math.round(detail.power.current_power / detail.power.max_power * 10000) / 100.00" :showText="false"
							:activeColor="'linear-gradient(90deg, #89D1F5 0%, #C4EFFA 100%)'" />
					</view>
					<view v-else class="fontText">
						能量已耗尽
					</view>
				</view>
			</view>
			<view class="propData" :style="detail.is_activate ? '' : 'margin-top: 180rpx'">
				<!-- <view class="vitality">
					<text>产生元气</text>
					<image src="/static/ble/vitality.png" mode=""></image>
					<u-count-to :start-val="10" :end-val="50" :duration="2000" :decimals="2" :useEasing="false">
					</u-count-to>
				</view> -->
				<u--image class="contImg" :src="detail.image" width="390rpx" height="460rpx"></u--image>
				<view class="propName">
					{{detail.name}}#{{detail.number}}
				</view>
				<u-button size="mini" shape="circle" :plain="true" @click="choose"
				customStyle="width: 160rpx;font-size:28rpx; height: 56rpx;color:#222222;background:transparent;border:1px solid #222222;" class="m-t-10">更换道具</u-button>
			</view>
			<view class="bottomCont">
				<view class="contBtn" @click="toMassage">
					{{detail.is_activate ? '开始艾灸' : '立即激活'}}
				</view>
			</view>
			<view class="promptCopy">
				<view class="">
					硬件断电将导致使用中断
				</view>
				<view class="">
					使用前可以考虑先充半小时电噢
				</view>
			</view>
			<u-popup ref="promptBox" :show="promptBox" overlayOpacity="0.8" round="20" mode="center"@close="promptBox = false">
				<view class="promptBox">
					<view class="promptText">
						<view class="text">
							{{popupObj.textOne}}
						</view>
						<view class="texts">
							{{popupObj.textTwo}} <text v-if="popupObj.tipstype" @click="onGotoRenew()">请点击续期</text>
						</view>
					</view>
					<view class="tipText" v-if="popupObj.stateType == 2">
						注：道具失效依旧可以正常使用实体硬件
					</view>
					<view class="btns">
						<view class="btns__one" @tap="onPopupLeftBtn()">
							{{popupObj.stateType == 1 ? '继续艾灸':'立即续期'}}
						</view>
						<!-- <view class="btns__two" @click="onGotoIn()" v-if="popupObj.stateType == 1">
							立即续期
						</view>
						<view class="btns__two" @click="onGotoRenew()" v-else-if="popupObj.stateType == 2 || popupObj.stateType == 3">
							立即续期
						</view> -->
						<view class="btns__two" @click="onGotoRenew()">
							立即续期
						</view>
					</view>
					<!-- 
					<view class="notes" v-if="popupObj.stateType == 1">
						注：能量每6小时刷新补充1/4
					</view> -->
				</view>
			</u-popup>
		</view>
		<example-popup ref="examplePopups" :datasIn="detail" :id="propId" @cancel="onCancel" @success="onSuccess"></example-popup>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		detailsr,
		massageReady,
		dormancyMassage
	} from '@/api/bluetooth.js'
	import Bluetooth from '@/pages/town/common/Bluetooth.js';
	import examplePopup from '@/pages/town/components/examplePopup.vue';
	let bluetooth = new Bluetooth();
	export default{
		data() {
			return{
				detail: {},
				id: 0,
				promptBox: false,
				popupObj:{//提示框
					textOne: '',//第一排字
					textTwo: '',//第二排字
					tipstype: false,//是否展示提示文字
					stateType: 0, //1为能量耗尽  2为时间过期 3时间过期无法维修
				},
				propId:'',//蓝牙道具id
			}
		},
		components: {
			examplePopup
		},
		onLoad(e) {
			this.id = e.id
			if(e.backType) this.backType = e.backType;
		},
		onShow() {
			setTimeout(()=>{
				this.onDormancyMassage()
			}, 400)
			this.onMessageReady()
		},
		methods: {
			//用户提示框左按钮
			onPopupLeftBtn() {
				switch (this.popupObj.stateType) {
					case 1:
						this.onToSearch();
						break;
					case 2:
					case 3:
						this.promptBox = false;
						break;
				}
			},
			//检测用户是否有未断开的设备
			async onDormancyMassage(){
				try {
					const datas = await dormancyMassage()
					this.bluetoothData = datas.data
					console.log('connectData', uni.getStorageSync('connectData'))
					console.log('dormancyMassage', datas)
					if(this.bluetoothData.is_show && !this.bluetoothData.is_end && JSON.stringify(uni.getStorageSync('connectData')) != '{}'){
						this.propId = this.bluetoothData.message_id
						console.log('propId', this.propId)
						this.$refs.examplePopups.onTipsrunt(true, '检测到你有未完成使用', `预使用完成可获得${this.bluetoothData.max_score}元气`, {textOne:'确认退出',textTwo:'重新连接'})
					}
				} catch (err) {
					console.log(err)
				}
			},
			//点击左侧按钮
			async onCancel(){
				this.$refs.examplePopups.onMessageEnd(uni.getStorageSync('connectData').massage_Type, '', 'index')
			},
			//点击右侧按钮并重新连接
			onSuccess(){
				let deviceId = uni.getStorageSync('connectData').deviceId
				bluetooth.openBluetoothAdapter().then((res) => {
					bluetooth.getBluetoothAdapterState().then((res) => {
						bluetooth.createBLEConnection(deviceId).then(res => {
							bluetooth.getBLEDeviceServices().then(service => {
								let i;
								if (uni.getSystemInfoSync().platform == 'android') {
									i = 0
									uni.setStorageSync('servicesId', service[i].uuid);
									bluetooth.getBLEDeviceCharacteristics(2).then(rest => {
										uni.setStorageSync('servicesId', service[2]
											.uuid); //安卓会返三个ID 需要拿第一个ID当作servicesId  第三个的ID拿取返回需要的值
										this.onResdBle();
									});
								} else {
									i = 0
									uni.setStorageSync('serviceId', service[i].uuid);
									this.onResdBle();
								}
							})
						}).catch((err) => {
							bluetooth.openBluetoothAdapter('蓝牙连接失败', 'none', 2000)
							setTimeout(()=>{
								uni.navigateTo({
									url: `/pages/town/ready?id=${uni.getStorageSync('connectData').id}`
								})
							}, 2000)
						})
					})
				}).catch((err) => {
					this.$refs.uToast.show({
						type: 'default',
						message: '蓝牙未打开'
					});
				})
			},
			//返回设备
			onResdBle() {
				bluetooth.getBLEDeviceCharacteristics().then(ints => {
					bluetooth.notifyBLECharacteristicValue().then(infos => {
						this.$refs.examplePopups.onSwitch(9, 'close')
						uni.navigateTo({
							url: `/pages/town/example/manipulation?id=${uni.getStorageSync('connectData').id}`,
							animationType: 'slide-in-right',
							animationDuration: 1000
						})
					}); //开始启用notify功能
				});
			},
			//返回上一页
			back() {
				if(this.backType == 1){
					uni.switchTab({
						url:'/pages/town/index'
					})
				} else {
					uni.navigateBack()
				}
			},
			async onMessageReady(){
				try{
					const res = await massageReady({props_id: parseInt(this.id)})
					this.detail = res.data
				}catch(e){
					console.log(e)
					uni.showToast({
						title: e.message || e.data,
						icon: 'none'
					})
					//TODO handle the exception
				}
			},
			choose() {
				uni.navigateTo({
					url: `./device?usedId=${this.id}&backType=${2}`
				})
			},
			async toMassage() {
				let nowTimes = Math.ceil(new Date().getTime() / 1000)
				if(!this.detail.power.current_power && this.detail.is_activate){
					await this.onStateType(1)
				} else if(nowTimes > this.detail.expiration_time && this.detail.is_activate){
					await this.onStateType(2)
				}
				this.onToSearch();
				// uni.navigateTo({
				// 	url: './example/components?id=' + this.id
				// })
			},
			onStateType(state){
				return new Promise(resolve => {
					this.popupObj.stateType = state
					let textOne, textTwo;
					console.log(112, this.popupObj.stateType)
					switch (this.popupObj.stateType) {
						case 1:
							textOne = '您的能量已耗尽'
							textTwo = '继续使用只获得经验值 不再获得元气'
							break;
						case 2:
							textOne = '此道具已过期 无法连接使用获得元气'
							textTwo = '若想继续获得元气'
							this.popupObj.tipstype = true
							break;
						case 3:
							textOne = '此道具已过期 无法维修'
							textTwo = '若想继续维修'
							this.popupObj.tipstype = true
							break;
						default:
							break;
					}
					this.popupObj.textOne = textOne
					this.popupObj.textTwo = textTwo
					this.promptBox = true
					return false
					resolve()
				})
			},
			onGoTo(){
				this.promptBox = false
				// uni.navigateTo({
				// 	url: './example/components?id=' + this.id
				// })
				this.onSearch();
			},
			//判断蓝牙地理位置初始化  并做后续操作
			async onToSearch() {
				if (uni.getSystemInfoSync().platform == 'android') {
					this.getLocation().then(res =>{
						this.onSearchs();
					}).catch((err) => {
						console.log(err)
						this.$refs.uToast.show({
							type: 'default',
							message: '请打开定位服务功能'
						});
					})
				} else {
					this.onSearchs();
				}
			},
			//点击续期
			onGotoRenew() {
				this.promptBox = false
				// uni.showToast({
				// 	title:'暂未开放，敬请期待~',
				// 	duration:3000,
				// 	icon:'none'
				// })
				// return false
				if (!uni.getStorageSync('renewalTypeState')) {
					this.$refs.examplePopups.onPopup()
					return;
				}
				this.$refs.examplePopups.onExtranetPage()
			},
			//安卓用户判断是否开启位置权限 若没开启低版本机型无法搜索到设备 嘻嘻
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: function(res) {
							var platform = res.platform;
							if (platform === 'android') {
								var context = plus.android.importClass("android.content.Context");
								var locationManager = plus.android.importClass(
									"android.location.LocationManager");
								var main = plus.android.runtimeMainActivity();
								var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									reject(false)
								} else {
									resolve(true)
								}
							}
						}
					})
				})
			},
			onSearchs() {
				bluetooth.openBluetoothAdapter().then((res) => {
					bluetooth.getBluetoothAdapterState().then((res) => {
						this.onSearch();
					})
				}).catch((err) => {
					this.$refs.uToast.show({
						type: 'default',
						message: '蓝牙未打开'
					});
				})
			},
			//跳转搜索蓝牙
			onSearch() {
				uni.navigateTo({
					url: `./example/search?id=${this.id}`,
					animationType: 'slide-in-right',
					animationDuration: 1000
				})
			},
		}
	}
</script>

<style lang="scss">
	.promptCopy{
		text-align: center;
		font-size: 28rpx;
		color: #b3b3b3;
		margin-top: 40rpx;
	}
	.ready{
		height: 100%;
		background: url('@/static/ble/pageImg/bg.png') no-repeat;
		background-size: 100%;
		.contents{
			padding: 22rpx 46rpx;
			.progressBar{
				display: flex;
				align-items: center;
				justify-content: center;
				// justify-content: space-between;
				margin-bottom: 120rpx;
				.progressBars{
					text-align: center;
					.fontText{
						font-size: 24rpx;
						color: #a2a2a2;
						margin-bottom: 16rpx;
					}
					.progress{
						border: 2rpx solid #EDF0F6;
						width: 236rpx;
						height: 22rpx;
						border-radius: 12rpx;
					}
				}
			}
			.propData{
				margin-bottom: 120rpx;
				text-align: center;
				.vitality {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 40rpx;
				
					image {
						width: 40rpx;
						height: 40rpx;
						margin: 0 12rpx 0 34rpx;
					}
				
					text {
						font-size: 36rpx;
						color: #000000;
					}
				}
				.contImg{
					margin-bottom: 60rpx;
					display: flex;
					align-items: center;
				}
				.propName{
					font-size: 36rpx;
					color: #000000;
				}
			}
			.bottomCont{
				.contBtn{
					background: #5CC9FF;
					color: #FFFFFF;
					padding: 22rpx 0;
					width: 100%;
					margin-bottom: 24rpx;
					border-radius: 50rpx;
					text-align: center;
				}
				.propPs{
					color: #a2a2a2;
					font-size: 24rpx;
					text-align: center;
				}
			}
		}
	}
	.promptBox {
		padding: 28rpx 80rpx 0rpx;
	
		.titles {
			font-size: 32rpx;
			font-weight: 700;
			text-align: center;
			margin-bottom: 32rpx;
		}
	
		.promptText {
			font-size: 32rpx;
			margin-bottom: 42rpx;
			text-align: center;
	
			.text {
				margin-bottom: 24rpx;
			}
		}
	
		.btns {
			text-align: center;
			border-radius: 100rpx;
			margin: 0 auto 20px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			&__one{
				background: #f7f7f7;
				color: #8e8e8e;
				border-radius: 50rpx;
				width: 45%;
				padding: 20rpx 0;
			}
			&__two{
				background: #5EB2FF;
				color: #FFFFFF;
				border-radius: 50rpx;
				width: 45%;
				padding: 20rpx 0;
			}
		}
		.notes{
			text-align: center;
			font-size: 28rpx;
			color: #b1b1b1;
		}
	}
</style>